<?php

namespace app\company\controller;

use app\company\model\SupplierDividend;
use app\company\validate\PartnerDividendValidate;
use app\service\traits\Crud;
use app\company\model\PartnerDividend as PartnerDividendModel;
use app\supplier\model\StatSupplier;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;
use app\company\model\CompanyUser;
use app\company\model\CompanyUserDividend;
use app\company\model\Supplier;

class PartnerDividend extends Base
{
    private PartnerDividendModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new PartnerDividendModel();
        $this->validateClass = PartnerDividendValidate::class;
        $this->isGs          = true;
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $item->date = date('Y-m', strtotime($item->date));
        });
    }

    /**
     * 用户分红列表
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userList(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene('list')->check($param);
        $sql   = new CompanyUser();
        $sql   = $sql->gs($this->company_id)->withSearch('real_name,mobile,identity', $param);
        $sql   = $sql->field('id,real_name,mobile,identity')->where('identity', '<>', 1);
        $count = $sql->count();
        if (Request::param('is_export', 0) != 1) $sql = $sql->page($param['page'], $param['limit']);
        $list = $sql->order($this->orderSort)->select()->each(function ($item) {
            //累计分红金额
            $item->dividend_amount = $item->companyUserDividends()->sum('amount');
        })->append(['identity_supplier_text']);
        return $this->success('获取成功', compact('count', 'list'));
    }

    /**
     * 用户分红明细
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userDividendDetail(): Response
    {
        $param = $this->request->param();
        $sql   = new CompanyUserDividend();
        $field = 'id,company_user_id,amount,create_time,company_id,turnover,supplier_id';
        $sql   = $sql->field($field)->withSearch('create_time,company_user_id', $param);
        if (Request::param('ids', 0)) $sql->whereIn('id', $param['ids']);//分页导出时用
        $count = $sql->count();
        if (Request::param('is_export', 0) != 1) $sql = $sql->page($param['page'], $param['limit']);
        $list = $sql->order($this->orderSort)->select()->each(function ($item) {
            $item->supplier_name = '全部经销商';
            if ($item->supplier_id) {
                $item->supplier_name = Supplier::where('id', $item->supplier_id)->value('name');
            }
        });
        return $this->success('获取成功', compact('count', 'list'));
    }

    /**
     * 开始分红
     * @return Response
     */
    public function dividend(): Response
    {
        $this->model->startTrans();
        try {
            $param = $this->request->param();
            validate($this->validateClass)->scene('dividend')->check($param);
            //得到当前数据
            $data = $this->model->where('id', $param['id'])->find();
            if ($data->dividend_status == 2) return $this->error('分红已结束');
            $money = $data->money;//总分红金额


            //职能部门人员分红  分红基数金额的10%平分
            $departmentMoney = $money * 0.1;
            $this->department($departmentMoney, $data);
            $money = $money - $departmentMoney;

            //市场招商人员分红
            //得到所有公司的分红金额
            //获取公司下经销商列表
            $supplierIds = Supplier::where('company_id', $data->company_id)->column('id');
            $year     = date('Y', strtotime($data->date));
            $month    = date('m', strtotime($data->date));
            $field    = 'sales_amount,supplier_id';
            $supplier = StatSupplier::where('year', $year)->whereIn('supplier_id',$supplierIds)->where('month', $month)->type(3)->field($field)->select()->each(function ($item) {
                $supplier                = SupplierDividend::supplierId($item->supplier_id)->find();
                $item->investor_id       = $supplier->investor_id;
                $item->investor_ratio    = $supplier->investor_ratio;//招商人分红比例
                $item->investor_dividend = $supplier->investor_ratio * $item->sales_amount / 100;//招商人分红基数
                $item->service_id        = $supplier->service_id;
                $item->service_ratio     = $supplier->service_ratio;//服务人分红比例
                $item->service_dividend  = $supplier->service_ratio * $item->sales_amount / 100;//服务人员分红基数
                $item->department_ratio  = $supplier->department_ratio;//职能部门分红比例
                $item->partner_id        = $supplier->partner_id;//合伙人
                $item->partner_ratio     = $supplier->partner_ratio;//合伙人分红比例
                $item->partner_dividend  = $supplier->partner_ratio * $item->sales_amount / 100;//合伙人经销商分红基数
                $item->total_dividend    = $item->investor_dividend + $item->service_dividend + $item->partner_dividend;//经销商分红总基数
            })->toArray();

            //总分红基数
            $total_dividend = array_sum(array_column($supplier, 'total_dividend'));

            $array = [];
            foreach ($supplier as $item) {
                if (!Supplier::where('id', $item['supplier_id'])->value('id')) continue;//已删除经销商不计算在内
                $arr['company_id']  = $this->company_id;
                $arr['supplier_id'] = $item['supplier_id'];
                $arr['turnover']    = $item['sales_amount'];
                //招商分红记录
                $arr['money']           = $money;
                $arr['company_user_id'] = $item['investor_id'];
                $arr['dividend_ratio']  = $item['investor_ratio'];
                $arr['amount']          = floor(($item['investor_dividend'] / $total_dividend) * $money * 100) / 100;
                (new CompanyUserDividend)->create($arr);
                //服务分红记录
                $arr['company_user_id'] = $item['service_id'];
                $arr['dividend_ratio']  = $item['service_ratio'];
                $arr['amount']          = floor(($item['service_dividend'] / $total_dividend) * $money * 100) / 100;
                (new CompanyUserDividend)->create($arr);
                //合伙人分红记录
                $arr['company_user_id'] = $item['partner_id'];
                $arr['dividend_ratio']  = $item['partner_ratio'];
                $arr['amount']          = floor(($item['partner_dividend'] / $total_dividend) * $money * 100) / 100;
                (new CompanyUserDividend)->create($arr);
            }
            //更新分红状态
            $data->dividend_status = 2;
            $data->save();
            $this->model->commit();
            return $this->success('分红成功');
        } catch (Exception $e) {
            $this->model->rollback();
            return $this->error('分红失败');
        }
    }


    /**
     * 职能部门分红  职能部门没有supplier_id 已和产品确认
     * @param $allMoney
     * @param $data
     * @return void
     * @throws Exception
     */
    public function department($allMoney, $data): void
    {
        $count = CompanyUser::where('identity', 2)->gs($this->company_id)->status(1)->count();
        // 保留两位小数并向下取整
        $money = floor(($allMoney / $count) * 100) / 100;
        $arr   = CompanyUser::where('identity', 2)->gs($this->company_id)->field('id')->status(1)->select()->each(function ($item) use ($money, $data) {
            $item->company_user_id = $item->id;
            $item->company_id      = $this->company_id;
            $item->turnover        = $data->turnover;
            $item->cost            = $data->cost;
            $item->dividend_ratio  = $data->dividend_ratio;
            $item->money           = $data->money;
            $item->amount          = $money;
            unset($item->id);
        });
        (new CompanyUserDividend)->saveAll($arr->toArray());
    }
}